<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>接雨水动画演示</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
            max-width: 100%;
            overflow-x: hidden;
        }
        .container {
            position: relative;
            height: 400px;
            margin: 20px 0;
            border: 1px solid #ddd;
            padding: 5px;
        }
        .bar {
            position: absolute;
            bottom: 0;
            background: #b3d9ff;
            transition: all 0.3s;
            text-align: center;
        }
        .water {
            position: absolute;
            bottom: 0;
            background: rgba(0, 191, 255, 0.5);
            transition: all 0.3s;
        }
        /* 指针样式 */
        .pointer {
            position: absolute;
            bottom: -20px;
            width: 20px;
            height: 20px;
            background: red;
            border-radius: 50%;
            transition: all 0.3s;
        }
        #left-pointer { background: #ff4444; }
        #right-pointer { background: #4444ff; }
        /* 状态栏 */
        .status {
            padding: 10px;
            background: #f0f0f0;
            margin: 10px 0;
        }
        #solution {
            padding: 10px;
            border: 1px solid #ddd;
            font-size: 14px;
        }
        button {
            padding: 8px 15px;
            margin: 5px;
            font-size: 14px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }


                .bar {
            position: absolute;
            bottom: 0;
            background: #b3d9ff;
            transition: all 0.3s;
            text-align: center;
            z-index: 1; /* 新增：柱子显示在上方 */
        }

        .water {
            position: absolute;
            bottom: 0;
            background: rgba(0, 191, 255, 0.3);
            transition: all 0.3s;
            z-index: 0; /* 新增：水区域显示在下方 */
        }
        .current-water {
            background: rgba(0, 191, 255, 0.8); /* 当前储水 */
        }
    </style>
</head>
<body>
    <h2 style="color: cadetblue; text-align: center">接雨水算法演示</h2>
    <div class="container" id="chart"></div>
    <div class="status">
        <div>Left Max: <span id="left-max">0</span></div>
        <div>Right Max: <span id="right-max">0</span></div>
        <div>Current Water: <span id="current-water">0</span></div>
        <div>Total Water: <span id="total-water">0</span></div>
    </div>
    <div style="text-align: center; margin: 20px 0">
        <button onclick="startAnimation()">开始演示</button>
        <button onclick="togglePause()">暂停</button>
        <button onclick="resetAnimation()">重置</button>
    </div>

<script>
let isPaused = false;
let animationSpeed = 500; // 动画速度（毫秒）
const height = [0,1,0,2,1,0,1,3,2,1,2,1]; // 示例输入数据

// 初始化动画
function initChart() {
    const container = document.getElementById('chart');
    container.innerHTML = '';
    const barWidth = container.offsetWidth / height.length;

    height.forEach((h, i) => {
        const bar = document.createElement('div');
        bar.className = 'bar';
        bar.style.width = barWidth + 'px';
        bar.style.height = h * 20 + 'px'; // 缩放高度
        bar.style.left = (i * barWidth) + 'px';
        bar.textContent = h;
        container.appendChild(bar);
    });

    // 创建指针
    ['left', 'right'].forEach(ptr => {
        const pointer = document.createElement('div');
        pointer.className = `pointer ${ptr}-pointer`;
        pointer.id = `${ptr}-pointer`;
        container.appendChild(pointer);
    });
}

// 更新指针位置
function updatePointers(left, right) {
    const container = document.getElementById('chart');
    const barWidth = container.offsetWidth / height.length;

    document.getElementById('left-pointer').style.left = (left * barWidth) + 'px';
    document.getElementById('right-pointer').style.left = (right * barWidth) + 'px';
}

// 显示当前储水区域
// 修改后的 highlightWater 函数
function highlightWater(left, right, currentWater) {
    const container = document.getElementById('chart');
    const barWidth = container.offsetWidth / height.length;

    // 创建新水区域（保留历史记录）
    const water = document.createElement('div');
    water.className = 'water'; // 基础样式（历史储水）
    water.style.width = (right - left + 1) * barWidth + 'px';
    water.style.height = Math.min(height[left], height[right]) * 20 + 'px';
    water.style.left = (left * barWidth) + 'px';

    // 为当前水区域添加高亮类
    water.classList.add('current-water');
    container.appendChild(water);
}

// 更新状态栏
function updateStatus(leftMax, rightMax, current, total) {
    document.getElementById('left-max').textContent = leftMax;
    document.getElementById('right-max').textContent = rightMax;
    document.getElementById('current-water').textContent = current;
    document.getElementById('total-water').textContent = total;
}

// 暂停/继续控制
function togglePause() {
    isPaused = !isPaused;
    const btn = document.querySelector("button[onclick='togglePause()']");
    btn.textContent = isPaused ? "继续" : "暂停";
}

// 延迟函数
function delay() {
    return new Promise(resolve => setTimeout(resolve, animationSpeed));
}

// 处理暂停逻辑
async function handlePause() {
    while (isPaused) {
        await new Promise(resolve => requestAnimationFrame(resolve));
    }
}

// 修改后的 highlightWater 函数
//         function highlightWater(left, right, currentWater) {
//             const container = document.getElementById('chart');
//             const barWidth = container.offsetWidth / height.length;
//
//             const water = document.createElement('div');
//             water.className = 'water';
//             water.style.width = (right - left + 1) * barWidth + 'px';
//             // 修正水高度：基于左右指针的最大值的最小值
//             const waterHeight = Math.min(leftMax, rightMax) * 20;
//             water.style.height = waterHeight + 'px';
//             water.style.left = (left * barWidth) + 'px';
//             water.classList.add('current-water');
//             container.appendChild(water);
//         }

        // 修改后的 runAnimation 函数（确保 leftMax 和 rightMax 在调用 highlightWater 前已更新）
      async function runAnimation() {
    let left = 0, right = height.length - 1;
    let leftMax = 0, rightMax = 0, total = 0;

    while (left <= right) {
        await handlePause();

        // 更新最大值
        leftMax = Math.max(leftMax, height[left]);
        rightMax = Math.max(rightMax, height[right]);

        // 更新指针和状态
        updatePointers(left, right);
        updateStatus(leftMax, rightMax, 0, total);
        await delay();

        if (leftMax < rightMax) {
            const current = leftMax - height[left];
            total += current;
            updateStatus(leftMax, rightMax, current, total);
            await delay();
            left++;
            highlightWater(left - 1, right + 1, current); // 指针移动后再高亮显示
        } else {
            const current = rightMax - height[right];
            total += current;
            updateStatus(leftMax, rightMax, current, total);
            await delay();
            right--;
            highlightWater(left - 1, right + 1, current); // 指针移动后再高亮显示
        }
    }
    updateStatus(leftMax, rightMax, 0, total);
    alert("演示完成！总储水量：" + total);
}


// 主动画函数
// 修改后的 runAnimation 函数
// async function runAnimation() {
//     let left = 0, right = height.length - 1;
//     let leftMax = 0, rightMax = 0, total = 0;
//
//     while (left <= right) {
//         // 新增：每次循环开始检查暂停状态
//         await handlePause();
//
//         // 更新左右最大值
//         leftMax = Math.max(leftMax, height[left]);
//         rightMax = Math.max(rightMax, height[right]);
//
//         // 更新指针和状态
//         updatePointers(left, right);
//         updateStatus(leftMax, rightMax, 0, total);
//         await delay();
//
//         if (leftMax < rightMax) {
//             // 计算当前储水并移动左指针
//             const current = leftMax - height[left];
//             total += current;
//             highlightWater(left, right, current);
//             updateStatus(leftMax, rightMax, current, total);
//             await delay();
//             left++;
//         } else {
//             // 计算当前储水并移动右指针
//             const current = rightMax - height[right];
//             total += current;
//             highlightWater(left, right, current);
//             updateStatus(leftMax, rightMax, current, total);
//             await delay();
//             right--;
//         }
//     }
//     updateStatus(leftMax, rightMax, 0, total);
//     alert("演示完成！总储水量：" + total);
// }



// 启动动画
function startAnimation() {
    initChart();
    resetStatus();
    runAnimation();
}

// 重置状态
function resetAnimation() {
    document.getElementById('chart').innerHTML = '';
    updateStatus(0, 0, 0, 0);
    initChart();
}

function resetStatus() {
    document.getElementById('left-max').textContent = 0;
    document.getElementById('right-max').textContent = 0;
    document.getElementById('current-water').textContent = 0;
    document.getElementById('total-water').textContent = 0;
}

// 初始化
initChart();
</script>
</body>
</html>
